<?php
include_once('./modules/head.php');
require_once('./db/pdo.php');
require_once('./users/users.php');

$id = $_GET['id'];

$user = getUserById($id, $dbh);

$user = $user->fetchAll();

$imageLocation = '';

if ((isset($_FILES['picture'])) && (!empty($_FILES['picture']['full_path'])))
{
    $imageLocation = uploadImage($_FILES['picture'], $id);
}


if (empty($user))
{
    //TODO: redirect to non-existed page
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $user['email'] = $_POST['email'];
    $user['phone'] = $_POST['phone'];
    $user['name'] = $_POST['name'];
    $user['username'] = $_POST['username'];
    $user['website'] = $_POST['website'];
    $user['image'] = $imageLocation;

    updateUser($user, $id, $dbh);
}
?>
<div class="container">
    <form class="row g-1" method="post" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="inputEmail" class="form-label">Email address</label>
            <input type="email" class="form-control" id="inputEmail" name="email" value="<?= $user[0]['email'] ?>">
        </div>
        <div class="mb-3">
            <label for="inputPassword" class="form-label">Phone</label>
            <input type="phone" class="form-control" id="inputPassword" name="phone" value="<?= $user[0]['phone'] ?>">
        </div>
        <div class="mb-3">
            <label for="exampleInputEmail1" class="form-label">Name</label>
            <input type="text" class="form-control" id="exampleInputEmail1" name="name" value="<?= $user[0]['name'] ?>">
        </div>
        <div class="mb-3">
            <label for="exampleInputEmail1" class="form-label">Username</label>
            <input type="text" class="form-control" id="exampleInputEmail1" name="username" value="<?= $user[0]['username'] ?>">
        </div>
        <div class="mb-3">
            <label for="exampleInputEmail1" class="form-label">Website</label>
            <input type="text" class="form-control" id="exampleInputEmail1" name="website" value="<?= $user[0]['website'] ?>">
        </div>
        <div class="input-group mb-3">
            <label class="input-group-text" for="inputGroupFile01">Upload</label>
            <input type="file" class="form-control" id="inputGroupFile01" name="picture">
        </div>
        <div class="col-10">
            <button class="btn btn-primary" type="submit">Submit form</button>
        </div>
        <div class="col-2" style="text-align: right;">
            <a href="./index.php" class="btn btn-danger">Back to users list</a>
        </div>        
    </form>    
</div>